//use yew::prelude::*;
use yew::virtual_dom::{VNode, VList};
use serde::{ser, de};
use js_sys::Date;
use crate::{
    types::SwapData,
    crypt,
    json::JsonPager,
    web::{LocalStorage, Console},
};

pub trait DataTable {

    fn get_pager<T: ser::Serialize + de::DeserializeOwned>(key: &'static str) -> Option<JsonPager<T>> {
        if let Some(v) = LocalStorage::get::<JsonPager<T>>(key) {
            if Date::now() / 1000.0 - v.time < 30.0 { //如果缓存在30秒之内, 则不重新请求服务器
                Some(v)
            } else { None }
        } else { None }
    }

    fn fetch_pager<T: ser::Serialize + de::DeserializeOwned>(response: Result<SwapData, anyhow::Error>, key: &'static str) -> Option<JsonPager<T>> {
        let data = if let Ok(v) = response { v } else {
            Console::error("获取服务端返回的数据时出错");
            return None;
        };
        if let Ok(mut v) = crypt::decrypt::<JsonPager<T>>(&data) {
            v.time = Date::now() / 1000.0; //设置刷新时间
            LocalStorage::set::<JsonPager<T>>(key, &v);
            Some(v)
        } else {
            Console::error("对于返回信息进行解密失败");
            None
        }
    }

    fn init_rows<T: ser::Serialize + de::DeserializeOwned>(pager: &Option<JsonPager<T>>, callback: fn(&T) -> VNode) -> VList {
        let mut rows = VList::new();
        if let &Some(p) = &pager {
            if let &Some(ref rs) = &p.rows {
                for r in rs {
                    rows.add_child(callback(&r));
                }
            }
        }

        rows
    }
}
